package com.glkj.vipsystem.modules.app.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.entity.ao.*;
import com.glkj.vipsystem.modules.ServiceResult;
import com.glkj.vipsystem.modules.app.annotation.LoginIgnore;
import com.glkj.vipsystem.modules.app.annotation.LoginUser;
import com.glkj.vipsystem.modules.app.form.BaseForm;
import com.glkj.vipsystem.service.IOrderGoodsService;
import com.glkj.vipsystem.service.IOrderService;
import com.glkj.vipsystem.service.IServiceApplyService;
import com.glkj.vipsystem.service.IVipCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户端API
 *
 * @author limuchan
 */
@Api(tags = "用户端API")
@RestController
@RequestMapping("/api/member")
public class AppMemberController extends AbstractAppController {
    @Resource
    private IVipCardService vipCardService;
    @Resource
    private IOrderService orderService;
    @Resource
    private IOrderGoodsService orderGoodsService;
    @Resource
    private IServiceApplyService serviceApplyService;


    @ApiOperation(value = "用户信息")
    @GetMapping("/info")
    public ServiceResult<MemberAO> info(@ApiIgnore @LoginUser MemberAO member) {
        return ServiceResult.ok(member);
    }

    @ApiOperation(value = "我的会员卡")
    @GetMapping("/vipCard/list")
    public ServiceResult<List<VipCardAO>> vipCardList(@ApiIgnore @LoginUser MemberAO member) {
        List<VipCardAO> list = vipCardService.selectList(
                new EntityWrapper<VipCardAO>()
                        .orderBy("id desc")
                        .setSqlSelect("*,(select company_name from t_company where id = t_vip_card.company_id) as company_name," +
                                "(select shop_name from t_shop where id = t_vip_card.shop_id) as shop_name")
                        .eq("member_id", member.getId())
        );
        return ServiceResult.ok(list);
    }

    @ApiOperation(value = "消费记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间范围(yyyy-MM-dd~yyyy-MM-dd)", paramType = "query"),
            @ApiImplicitParam(name = "vipCardId", value = "会员卡id(可以按会员卡来筛选)", paramType = "query")
    })

    @GetMapping("/consume/record")
    public ServiceResult<Map<String, Object>> consumeRecord(@ApiIgnore @LoginUser MemberAO member, BaseForm form
            , String time, Integer vipCardId) {
        Map<String, Object> data = new HashMap<>();
        Wrapper<OrderAO> wrapper = new EntityWrapper<OrderAO>()
                .orderBy("id desc");
        wrapper.where("(member_mobile = '" + member.getMobile() + "'" +
                " or member_id = '" + member.getId() + "')");
        if (StringUtils.isNotBlank(time) && time.contains("~")) {
            String[] timeRange = time.split("~");
            wrapper.between("create_time", timeRange[0].trim(), timeRange[1].trim() + " 23:59:59");
        }
        if (vipCardId != null) {
            wrapper.eq("vip_card_id", vipCardId);
        }
        Page<OrderAO> page = orderService.selectPage(
                new Page<>(form.getPage(), form.getPageSize()),
                wrapper
        );
        data.put("pageData", new PageUtils(page));
        // 计算加总
        BigDecimal orderAmount = (BigDecimal) orderService.selectObj(
                wrapper.setSqlSelect("sum(order_amount) as orderAmount")
        );
        if (orderAmount == null) {
            orderAmount = BigDecimal.ZERO;
        }
        data.put("orderAmount", orderAmount);
        return ServiceResult.ok(data);
    }

    @ApiOperation(value = "消费明细")
    @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "path", dataType = "long", required = true)
    @GetMapping("/consume/detail/{orderId}")
    public ServiceResult<Map<String, Object>> consumeRecord(@PathVariable("orderId") Long orderId) {
        if (orderId == null) {
            return ServiceResult.error("请选择要查看的消费记录");
        }
        Map<String, Object> data = new HashMap<>();
        OrderAO orderAO = orderService.selectById(orderId);
        if (orderAO == null) {
            return ServiceResult.error("消费记录不存在");
        }
        data.put("order", orderAO);
        List<OrderGoodsAO> orderGoodsAOS = orderGoodsService.selectByOrder(orderId);
        data.put("goodsList", orderGoodsAOS);
        return ServiceResult.ok(data);
    }

    @LoginIgnore
    @ApiOperation(value = "购买服务")
    @PostMapping("/service/apply")
    public ServiceResult<Boolean> serviceApply(@RequestBody ServiceApplyAO form) {
        ValidatorUtils.validateEntity(form);
        form.setCreateTime(new Date());
        serviceApplyService.insert(form);
        return ServiceResult.ok(true);
    }

}
